import os
import re
import chardet
import tkinter as tk
from tkinter import filedialog, messagebox
import webbrowser

# kui-novel-arrange
# 奎歪歪的小说整理 脚本
# 奎歪歪的小说整理工具整合版
# 本文件为Beta版本 新功能测试完成后会同步到正式版本


# 参数设置
directory_path = ""  # 指定目录路径
indented_paragraph_setting = "    "  # 缩进参数
paragraph_spacing_setting = "\n\n"  # 段落间距参数


def detect_encoding(file_path):
    with open(file_path, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']
        confidence = result['confidence']
        return encoding, confidence


def format_text_files(directory, enable_newline_handling=False, enable_paragraph_splitting=False,
                      include_subdirectories=False, encoding_table=None, formatted_count=0, file_count=0):
    if encoding_table is None:
        encoding_table = {}

    # 统计目录下的txt文件数量
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            file_count += 1

    # 遍历目录下的txt文件
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            filepath = os.path.join(directory, filename)

            # 检测文件编码

            encoding, confidence = detect_encoding(filepath)
            if encoding is None:
                print(f"无法检测文件编码: {filename}")
                continue

            # 记录文件编码到编码表
            if encoding not in encoding_table:
                encoding_table[encoding] = 1
            else:
                encoding_table[encoding] += 1

            with open(filepath, "r", encoding=encoding, errors='ignore') as file:
                content = file.read()

            # 段落分割处理
            if enable_paragraph_splitting:
                content = re.sub(r'(?<=\S)(?=\s{2,})', paragraph_spacing_setting, content)

            # 格式整理
            formatted_content = ""
            paragraphs = re.split("\n\n+", content)
            for paragraph in paragraphs:
                if enable_newline_handling:
                    paragraph = re.sub("\n+", " ", paragraph)  # 删除段落中的换行符
                if paragraph.strip():  # 检查段落是否为空
                    indented_paragraph = indented_paragraph_setting + paragraph.strip()
                    formatted_content += indented_paragraph + paragraph_spacing_setting
                else:
                    formatted_content += paragraph_spacing_setting

            # 将整理后的内容写回文件
            with open(filepath, "w", encoding=encoding) as file:
                file.write(formatted_content)

            formatted_count += 1

            # 显示整理进度
            progress_text = f"正在整理文件: {filename}\n已整理完的文件数量: {formatted_count}/{file_count}"
            print(progress_text)
            progress_label.config(text=progress_text)
            progress_label.update()

            # 打印文件编码表，检查处理后文件编码是否出现问题
            encoding_table_text = "文件编码表:\n"
            for encoding, count in encoding_table.items():
                encoding_table_text += f"编码: {encoding}, 数量: {count}\n"
            encoding_label.config(text=encoding_table_text)

    # 处理子目录
    if include_subdirectories:
        for root, dirs, files in os.walk(directory):
            for dir_name in dirs:
                dir_path = os.path.join(root, dir_name)
                formatted_count, file_count = format_text_files(dir_path, enable_newline_handling,
                                                                enable_paragraph_splitting, include_subdirectories,
                                                                encoding_table, formatted_count, file_count)

    return formatted_count, file_count


def browse_directory():
    directory = filedialog.askdirectory(title="选择目录")
    if directory:
        enable_newline_handling = newline_handling_var.get() == 1
        enable_paragraph_splitting = paragraph_splitting_var.get() == 1
        include_subdirectories = subdirectory_handling_var.get() == 1
        formatted_count, file_count = format_text_files(directory, enable_newline_handling, enable_paragraph_splitting,
                                                        include_subdirectories)
        messagebox.showinfo("整理完成", f"文件整理完成！共处理了{formatted_count}个文件。")


def open_link(event):
    webbrowser.open("https://gitee.com/kuiwaiwai")


# 创建GUI窗口
window = tk.Tk()

window.title("小说整理工具 kui-novel-arrange")

window.geometry("400x320")

# 创建选择目录按钮
browse_button = tk.Button(window, text="选择目录", command=browse_directory)
browse_button.pack()

# 创建复选框和标签
newline_handling_var = tk.IntVar()
newline_handling_checkbox = tk.Checkbutton(window, text="段中换行处理", variable=newline_handling_var)
newline_handling_checkbox.pack()

paragraph_splitting_var = tk.IntVar()
paragraph_splitting_checkbox = tk.Checkbutton(window, text="分割段落", variable=paragraph_splitting_var)
paragraph_splitting_checkbox.pack()

subdirectory_handling_var = tk.IntVar()
subdirectory_handling_checkbox = tk.Checkbutton(window, text="处理子目录", variable=subdirectory_handling_var)
subdirectory_handling_checkbox.pack()

# 创建进度标签
progress_label = tk.Label(window, text="等待选择目录...")
progress_label.pack()

# 创建文件编码标签
encoding_label = tk.Label(window, text="段中换行处理和分割段落只适用于特殊情况\n并且根据对应情况通常只需选择两项中的一项\n\n 选择目录后程序会立即开始执行\n请做好文件备份")
encoding_label.pack()

# 超链接标签
link_label = tk.Label(window, text="kuiwaiwai", fg="blue", cursor="hand2")
link_label.pack(pady=10)
link_label.bind("<Button-1>", open_link)

window.mainloop()